<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="excel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table v-loading="loading" border :data="list" :default-sort="{prop: 'workNumber'}">
          <el-table-column label="序号" type="index" width="100px" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scoped">
              <div>
                {{ enumerateFn(scoped.row.formOfEmployment) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="账户状态">
            <template slot-scope="scoped">
              <el-switch
                v-model="scoped.row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template slot-scope="scoped">
              <el-button type="text" size="small">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="delFn(scoped.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination layout="prev, pager, next" :total="total" :page-size="params.size" :current-page="params.page" @current-change="currentChangeFn" />
        </div>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="off">
        <AddEmployee ref="AddEmployee" @close="close" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import AddEmployee from './addEmployee'
import { reqGetEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
console.log(EmployeeEnum)
const hierType = {}
EmployeeEnum.hireType.forEach(item => {
  hierType[item.id] = item.value
})
export default {
  components: {
    AddEmployee
  },
  data() {
    return {
      list: [],
      params: {
        page: 1, // 当前页
        size: 5 // 每页条数
      },
      total: 0, // 总数
      loading: false,
      showDialog: false
    }
  },
  created() {
    this.getEmployeeListFn()
  },
  methods: {
    // 获取员工列表
    async getEmployeeListFn() {
      this.loading = true
      const res = await reqGetEmployeeList(this.params)
      this.list = res.data.rows
      this.total = res.data.total
      console.log(this.list.enableState)
      this.loading = false
    },
    // 枚举
    enumerateFn(id) {
      return hierType[id]
    },
    // 分页点击
    currentChangeFn(newPage) {
      this.params.page = newPage
      this.getEmployeeListFn()
    },
    // 删除员工 (封装方法)
    async del(id) {
      try {
        const rs = await delEmployee(id)
        console.log('删除之后的结果是', rs)
        // 1. 提示
        this.$message.success('删除成功')
        // 判断
        if (this.list.length === 1) {
          this.params.page = (this.params.page - 1) || 1
        }
        // 2. 重新加载数据
        this.getEmployeeListFn()
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // 点击删除
    delFn(id) {
      this.$confirm('你确定要删除吗').then(() => {
        this.del(id)
      }).catch(() => {

      })
    },
    // 点击确定
    close() {
      this.showDialog = false
      this.getEmployeeListFn()
    },
    // 关闭弹窗 重置数据
    off() {
      this.$refs.AddEmployee.reset()
    },

    transData(arr) {
      // 把formOfEmployment中的1改成正式， 2改成非正式
      arr.forEach(item => {
        if (item.formOfEmployment) {
          // 1 --> 正式
          // 2 --> 非正式
          item.formOfEmployment = hierType[item.formOfEmployment]
        }
      })

      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 取出数组中第一个元素，来根据key生成对应的中文
      const first = arr[0]
      const header = Object.keys(first).map(item => map[item])
      console.log('表头是', header)
      const data = arr.map(obj => {
        return Object.values(obj)
      })
      console.log('数据是', data)
      return { header, data }
    },
    // 把当前页的数据导出来，保存成excel文件
    // 导出
    excel() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 1. 发请求，获取当前页的数据
        const rs = await reqGetEmployeeList(this.params)
        console.log('从后端获取的员工列表是', rs.data.rows)

        // 2. 修改一下数据格式，以便导出
        const { header, data } = this.transData(rs.data.rows)
        // 3. 导出
        excel.export_json_to_excel({
          header, // 表头 必填
          data,
          filename: 'test-export-excel',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    }
  }

}
</script>
